package com.hmall.gateway.filter;

import com.hmall.common.exception.UnauthorizedException;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.config.JwtProperties;
import com.hmall.gateway.utils.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    private final JwtProperties jwtProperties;
    private final AntPathMatcher antPathMatcher;
    private final JwtTool jwtTool;

    public AuthGlobalFilter(AuthProperties authProperties, JwtProperties jwtProperties, JwtTool jwtTool) {
        this.authProperties = authProperties;
        this.jwtProperties = jwtProperties;
        this.jwtTool = jwtTool;
        this.antPathMatcher = new AntPathMatcher();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //判断是否要进行登录的请求
        ServerHttpRequest request = exchange.getRequest();
        //如果不是则放行
        if (isExclude(request.getPath().toString())) {
            return chain.filter(exchange);
        }
        // 获取请求头的属性 authorization 的值就是令牌
        String token = request.getHeaders().getFirst("authorization");

        // 校验令牌
        try {
            Long userId = jwtTool.parseToken(token);

            //输出用户信息模拟将用户信息传到后端
            System.out.println("网关解析用户ID：" + userId);

            //将所需的信息保存到请求头中，改写request对象，设置请求头到后端的微服务
            ServerHttpRequest newRequest = request.mutate()
                    .header("user-info", userId.toString())
                    .build();
            
            // 使用新的request继续处理
            return chain.filter(exchange.mutate().request(newRequest).build());

        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }

        return path.contains("/api/user/login") || path.contains("/api/user/register");
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
